
# 帮我写个Python链接mysql库的操作，并执行增删改查操作. 数据库库名字为suchool，表名字为：student。


# pip install mysql-connector-python


import mysql.connector

# 建立数据库连接
cnx = mysql.connector.connect(
    host="localhost",
    user="your_username",
    password="your_password",
    database="school"
)



# 创建游标对象
cursor = cnx.cursor()

# 查询数据
def select_data():
    query = "SELECT * FROM student"
    cursor.execute(query)
    result = cursor.fetchall()
    for row in result:
        print(row)

# 插入数据
def insert_data(name, age, grade):
    query = "INSERT INTO student (name, age, grade) VALUES (%s, %s, %s)"
    values = (name, age, grade)
    cursor.execute(query, values)
    cnx.commit()
    print("数据插入成功")

# 更新数据
def update_data(student_id, new_name):
    query = "UPDATE student SET name = %s WHERE id = %s"
    values = (new_name, student_id)
    cursor.execute(query, values)
    cnx.commit()
    print("数据更新成功")

# 删除数据
def delete_data(student_id):
    query = "DELETE FROM student WHERE id = %s"
    values = (student_id,)
    cursor.execute(query, values)
    cnx.commit()
    print("数据删除成功")

# 调用函数进行操作
select_data()  # 查询数据

insert_data("John Doe", 20, "Senior")  # 插入数据

update_data(1, "Jane Smith")  # 更新数据

delete_data(2)  # 删除数据

# 关闭游标和数据库连接
cursor.close()
cnx.close()